package com.md.youyouhui.ui.home;

import android.databinding.DataBindingUtil;
import android.os.Build;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.md.youyouhui.R;
import com.md.youyouhui.databinding.ActivityWebNewsBinding;
import com.md.youyouhui.net.Constants;
import com.md.youyouhui.ui.BaseActivity;
import com.md.youyouhui.utils.SharedPreferencesUtils;
import com.md.youyouhui.utils.StatusBarHelper;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by AdministratorZJ
 * on 2019/4/24.
 */
public class WebNewsActivity extends BaseActivity {
    private ActivityWebNewsBinding newsBinding;
    @Override
    public void setContentLayout() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StatusBarHelper.setFullWindow(getWindow());
            StatusBarHelper.setStatusBarTextColor(getWindow(), false);
        }
        newsBinding = DataBindingUtil.setContentView(this, R.layout.activity_web_news);
    }

    @Override
    public void initView() {
        newsBinding.back.setOnClickListener(v -> finish());
    }

    @Override
    public void initData() {
        String token = SharedPreferencesUtils.getString(this, Constants.USER_TOKEN, "");
        String url = getIntent().getStringExtra("url");
        String title = getIntent().getStringExtra("title");
        WebSettings settings = newsBinding.webView.getSettings();
        settings.setJavaScriptEnabled(true);
        //在本界面展示
        newsBinding.webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        newsBinding.webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                newsBinding.setProgress(newProgress);
            }
        });
        Map<String, String> extraHeaders = new HashMap<>();
        extraHeaders.put("token", token);
        newsBinding.webView.loadUrl(url, extraHeaders);
        newsBinding.webView.addJavascriptInterface(new JsInterface(), "finishInterface");
    }

    public class JsInterface {
        @JavascriptInterface
        public void finishJS() {
            finish();
        }
    }
}
